package com.lc.fbtp.draftmsg.core.parse.paper;

import java.io.ByteArrayInputStream;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lc.fbtp.draftmsg.api.paper.MainBody;
import com.thoughtworks.xstream.XStream;

class DocumentParser {

	private static final Logger logger = LoggerFactory.getLogger(DocumentParser.class);
	private static DocumentParser parser = null;
	private DocumentParser(){}
	
	public static DocumentParser getInstance(){
		if(parser == null){
			parser = new DocumentParser();
		}
		return parser;
	}
	
	@SuppressWarnings("unchecked")
	public <T extends MainBody> BodyParseResult parse(String xml, Class<T> mainBodyClazz) throws Exception{
		com.lc.fbtp.draftmsg.api.paper.Document doc = new com.lc.fbtp.draftmsg.api.paper.Document();
		SAXReader saxReader = new SAXReader();
		try {
			BodyParseResult result = new BodyParseResult();
			Document document = saxReader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
			Element rootElement = document.getRootElement();
			for (Iterator<Element> i = rootElement.elementIterator(); i.hasNext();) {
				Element element = (Element) i.next();
				//解析MainBody报文体内容
				if("MainBody".equals(element.getName())){
					XStream xstream = new XStream();
					xstream.alias("MainBody", mainBodyClazz);
					xstream.autodetectAnnotations(Boolean.TRUE);
					T t = (T) xstream.fromXML(element.asXML());
					result.setMainBodyXmlStr(element.asXML());
					doc.setMainBody(t);
				}
				//解析CdesSgntr下行报文加签内容
				if("CdesSgntr".equals(element.getName())){
					doc.setCdesSgntr(element.getText());
				}
				//解析PtcptSgntr上行报文加签内容
				if("PtcptSgntr".equals(element.getName())) {
					doc.setPtcptSgntr(element.getText());
				}
			}
			result.setDocument(doc);
			return result;
		} catch (Exception e) {
			logger.error("报文解析失败:{}", xml);
			throw e;
		}
	}
	
}
